package com.admin.user.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;

import com.admin.user.config.ZhentaoException;
import com.admin.user.mapper.ArUserMapper;
import com.admin.user.service.ArUserService;
import com.admin.user.utlis.SaltUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.client.common.config.IdWorker;
import com.client.model.pojo.user.ArUser;
import com.client.model.system.*;
import com.client.model.vo.common.Result;
import com.client.model.vo.common.ResultCodeEnum;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
* @author liuwenju
* @description 针对表【ar_user】的数据库操作Service实现
* @createDate 2024-04-01 20:59:14
*/
@Service
public class ArUserServiceImpl extends ServiceImpl<ArUserMapper, ArUser>
    implements ArUserService {
    @Autowired
    private ArUserMapper arUserMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public boolean register(ArUser arUser) {
        String salt = SaltUtil.getSalt();
        IdWorker idWorker=new IdWorker();
        arUser.setUid(idWorker.nextId());
        arUser.setSalt(salt);
        String pass = DigestUtils.md5DigestAsHex((arUser.getPassword() + salt).getBytes());
        arUser.setPassword(pass);
        String s = redisTemplate.opsForValue().get(arUser.getMobile() + "_" + arUser.getSms());
        if (Objects.equals(arUser.getSms(), s)){
            return arUserMapper.insert(arUser) >=1;
        }
        return false;
    }

    @Override
    public ValidateCodeVo getValidateCode() {
        //定义图形验证码的长、宽、验证码字符数、干扰元素个数
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(150, 48, 4, 5);
        //获取验证码的值
        String code = captcha.getCode();
        //用来生成图片的base64字符串
        String imageBase64 = captcha.getImageBase64();
        //把验证码保存到redis 中
        String key = IdUtil.simpleUUID().replace("-", "");
        redisTemplate.opsForValue().set("validateCode:" + key, code, 1, TimeUnit.MINUTES);
        ValidateCodeVo validateCodeVo = new ValidateCodeVo();
        validateCodeVo.setCodeKey(key);
//        validateCodeVo.setCodeValue(imageBase64);

        validateCodeVo.setCodeValue("data:image/png;base64,"+imageBase64);
        //响应结果
        return validateCodeVo;

    }

    @Override
    public LoginVo phoneLogin(PhoneDto phoneDto) {
        //数据校验
        if (ObjectUtil.isEmpty(phoneDto)) {
            throw new ZhentaoException(ResultCodeEnum.DATA_ERROR);
        }
        String code = redisTemplate.opsForValue().get(phoneDto.getMobile() + "_" + phoneDto.getChk());

        if (StrUtil.isBlank(code)) {
            throw new ZhentaoException(ResultCodeEnum.CAPTCHA_ERROR);
        }
        if (!code.equalsIgnoreCase(phoneDto.getChk())) {
            throw new ZhentaoException(ResultCodeEnum.CAPTCHA_ERROR);
        }
        QueryWrapper queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("mobile",phoneDto.getMobile());
        ArUser user = arUserMapper.selectOne(queryWrapper);
        //生成token保存到redis  把用户信息保存到redis
        String token = IdUtil.simpleUUID().replace("-", "");
        //token有效时长30分钟
        redisTemplate.opsForValue().set("user:login"+token, JSON.toJSONString(user), 30, TimeUnit.MINUTES);
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setRefresh_token("");
        return loginVo;

    }

    @Override
    public Result updatePass(PassDto passDto) {
        QueryWrapper queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("real_name",passDto.getRealName());
        queryWrapper.eq("iden",passDto.getIden());
        ArUser arUser = arUserMapper.selectOne(queryWrapper);
        if(ObjectUtil.isEmpty(arUser)){
            return Result.build(false,202,"身份信息不匹配");
        }
//        System.out.println(passDto.getMobile());
//        System.out.println(passDto.getChk());
        String code = redisTemplate.opsForValue().get(passDto.getMobile() + "_" + passDto.getChk());
//        System.err.println(code);
        if (StrUtil.isBlank(code)) {
            return Result.build(false,ResultCodeEnum.VALIDATECODE_ERROR);
        }
        if (!code.equalsIgnoreCase(passDto.getChk())) {
            return Result.build(false,ResultCodeEnum.VALIDATECODE_ERROR);
        }
        String salt = SaltUtil.getSalt();
        arUser.setSalt(salt);
        String pass = DigestUtils.md5DigestAsHex((passDto.getPassword() + salt).getBytes());
//        System.out.println("111111"+pass);
        arUser.setPassword(pass);
        arUserMapper.updateById(arUser);
        return Result.build(true,ResultCodeEnum.SUCCESS);
    }

    @Override
    public void logout(String token) {
        //数据校验
        redisTemplate.delete("user:login:"+token);
    }

    @Override
    public LoginVo login(LoginDto loginDto) {
        //数据校验
        if (ObjectUtil.isEmpty(loginDto)) {
            List<String> s=new ArrayList<>();
            throw new ZhentaoException(ResultCodeEnum.DATA_ERROR);
        }
        //校验验证码
        if (StrUtil.isBlank(loginDto.getCaptcha())){
            throw  new ZhentaoException(ResultCodeEnum.CAPTCHA_ERROR);
        }
        //
        String vadlicode = redisTemplate.opsForValue().get("validateCode:" + loginDto.getCodeKey());
        if (StrUtil.isBlank(vadlicode)) {
            throw  new ZhentaoException(ResultCodeEnum.CAPTCHA_ERROR);
        }
        //校验验证码
        if (!vadlicode.equalsIgnoreCase(loginDto.getCaptcha())) {
            throw  new ZhentaoException(ResultCodeEnum.CAPTCHA_ERROR);
        }
        //校验手机号和密码
        if(ObjectUtils.isEmpty(loginDto.getMobile())){
            throw  new ZhentaoException(ResultCodeEnum.SYSTEM_ERROR);
        }
        //根据手机号查找出来salt
        QueryWrapper queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("mobile",loginDto.getMobile());
        ArUser arUser = arUserMapper.selectOne(queryWrapper);
        String salt = arUser.getSalt();
//        System.err.println(salt);
//        System.err.println(loginDto.getPassword());
        //密码和salt进行加密
        String password = DigestUtils.md5DigestAsHex((loginDto.getPassword() + salt).getBytes());
//        System.out.println(password);
        QueryWrapper query=new QueryWrapper<>();
        query.eq("password",password);
        query.eq("mobile",loginDto.getMobile());
        //查询
        ArUser user = arUserMapper.selectOne(query);
        if (ObjectUtils.isEmpty(user)){
            throw new RuntimeException("用户名或者密码错误");
        }
        //生成token保存到redis  把用户信息保存到redis
        String token = IdUtil.simpleUUID().replace("-", "");
        //token有效时长30分钟
        redisTemplate.opsForValue().set("user:login"+token, JSON.toJSONString(user), 30, TimeUnit.MINUTES);
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setRefresh_token("");
        return loginVo;
    }

    @Override
    public LoginUserVo getUserInfo(String token) {
        //数据校验
        if (StrUtil.isBlank(token)) {
            throw new RuntimeException("数据异常");
        }
        String userInfo = redisTemplate.opsForValue().get("user:login"+token);
        System.err.println("---------->token"+userInfo);
        if (StrUtil.isBlank(userInfo)) {
            throw new RuntimeException("用户名或者密码错误");
        }
        ArUser sysUser = JSON.parseObject(userInfo, ArUser.class);
        LoginUserVo userInfoVo = new LoginUserVo();
        BeanUtils.copyProperties(sysUser, userInfoVo);
        return userInfoVo;
    }

    @Override
    public Object haveMobile(Integer mobile) {
        QueryWrapper queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("mobile",mobile);
     return    arUserMapper.selectOne(queryWrapper);
    }

    @Override
    public ArUser forget(ArUser arUser) {
        QueryWrapper queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("mobile",arUser.getMobile());
        queryWrapper.eq("realname",arUser.getRealName());
        queryWrapper.eq("iden",arUser.getIden());
        return arUserMapper.selectOne(queryWrapper);
    }




}




